package cn.controller;

import cn.common.ConfigOption;
import cn.common.DocumentHandler;
import cn.common.ExceResult;
import cn.common.LayTable;
import cn.kpi.entity.attendance.AttSummaryEntity;
import cn.kpi.entity.sys.OrgEntity;
import cn.kpi.entity.usualassessment.*;
import cn.kpi.service.sys.IOrgService;
import cn.kpi.service.usualassessment.IUserUATZpService;
import com.alibaba.fastjson.JSON;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {

    @Autowired
    private IUserUATZpService userUATZpService;

    @Autowired
    private IOrgService iOrgService;

    @RequestMapping(value = "/index")
    public String Index(Model model) {

        model.addAttribute("year", 0);
        model.addAttribute("quarter", 0);
        return "statistics/peacetime";
    }

    @RequestMapping(value = "/peacetime")
    public String Index1(Model model, int year, int quarter) {


        model.addAttribute("year", year);
        model.addAttribute("quarter", quarter);
        return "statistics/peacetime";
    }


    @RequestMapping(value = "/bddc")
    public String bddc(Model model) {
        try {
            List<OrgEntity> orglst = getOrgEntitiesAll();//getOrgEntities();//按权限暂时取掉

            model.addAttribute("orglst", orglst);
            model.addAttribute("defaultValue", orglst.get(0).getOrgid());
        } catch (Exception ex) {


        }
        return "statistics/bddc";
    }

    @ResponseBody
    @RequestMapping(value = "/get_list")
    public PSKHResult GetList(HttpServletRequest request) {


        List<NewPSKH> lst = new ArrayList<>();
        PSKHResult result = new PSKHResult();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int quarter = Integer.parseInt(request.getParameter("quarter"));


          lst = userUATZpService.newpskhResult(year, quarter);
            List<UserCount> userCounts = userUATZpService.getUserCount();
            List<Map> maps = userUATZpService.bcjke(year, quarter);

            for (int i = 0; i < lst.size(); i++) {

                for (int j = 0; j < maps.size(); j++) {

                    if (maps.get(j).containsKey("rank")) {
                        if(maps.get(j).get("rank")!=null && maps.get(j).get("bcjkhrs")!=null && lst.get(i).getRank()!=null){
                        if (Integer.parseInt(maps.get(j).get("rank").toString()) == lst.get(i).getRank()) {
                            lst.get(i).setBcj(Integer.parseInt(maps.get(j).get("bcjkhrs").toString()));
                            }
                        }
                    }
                }
            }
            if (lst.size() <= 0) {
                lst = new ArrayList<>();
                for (int j = 0; j < maps.size(); j++) {

                    if (maps.get(j).containsKey("rank")) {

                        NewPSKH newPSKH = new NewPSKH();

                        newPSKH.setRank(Integer.parseInt(maps.get(j).get("rank").toString()));
                        newPSKH.setBcj(Integer.parseInt(maps.get(j).get("bcjkhrs").toString()));
                        lst.add(newPSKH);

                    }
                }

            }

            result.setNewPSKHS(lst);
//
            result.setUserCounts(userCounts);

            PSKHOpinion pskhOpinion = userUATZpService.getOpinion(year, quarter);
            result.setPskhOpinion(pskhOpinion);

        } catch (Exception e) {

            String mess = e.getMessage();

        }
        // return JsonMapper.toJsonString(countlist);
        //return countlist;
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/peace_export")
    public ExceResult exportOpinion(HttpServletRequest request) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);

        List<PSKH> lst = null;
        PSKHResult pskhResult = new PSKHResult();
        try {
            int year = Integer.parseInt(request.getParameter("year"));
            int quarter = Integer.parseInt(request.getParameter("quarter"));

            List<UserCount> userCounts = userUATZpService.getUserCount();
            lst = userUATZpService.pskhResult(year, quarter);
            PSKHOpinion pskhOpinion = userUATZpService.getOpinion(year, quarter);

            String month1 = "";
            String month2 = "";
            if (quarter == 1) {
                month1 = "1";
                month2 = "3";
            }
            if (quarter == 2) {
                month1 = "4";
                month2 = "6";
            }


            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("yearid", String.valueOf(year));
            dataMap.put("month1", month1);
            dataMap.put("month2", month2);
            dataMap.put("quarter", quarter);
            //map初始化
            for (int i = 0; i < 5; i++) {
                dataMap.put("good" + i, "");
                dataMap.put("pass" + i, "");
                dataMap.put("bad" + i, "");
                dataMap.put("nojoin" + i, "");
                dataMap.put("nosure" + i, "");
                dataMap.put("good" + i, "");
            }

            //总数
            int hj = 0;
            for (int i = 0; i < userCounts.size(); i++) {
                if (userCounts.get(i).getRank() != null && !userCounts.get(i).getRank().equals("5")) {
                    dataMap.put("sump" + userCounts.get(i).getRank(), userCounts.get(i).getNum());
                    hj += userCounts.get(i).getNum();
                }
            }
            dataMap.put("sump0", hj);

            Map<String, Integer> xiaoji = new HashMap<>();
            int hj1 = 0, hj2 = 0, hj3 = 0, hj4 = 0, hj5 = 0;
            for (int i = 0; i < lst.size(); i++) {
                PSKH item = lst.get(i);
                if (item.getZpjg().equals("好")) {
                    dataMap.put("good" + item.getRank(), item.getNum());
                    hj1 += item.getNum();
                }
                if (item.getZpjg().equals("合格")) {
                    dataMap.put("pass" + item.getRank(), item.getNum());
                    hj2 += item.getNum();
                }
                if (item.getZpjg().equals("差")) {
                    dataMap.put("bad" + item.getRank(), item.getNum());
                    hj3 += item.getNum();
                }
                if (item.getZpjg().equals("不参加")) {
                    dataMap.put("nojoin" + item.getRank(), item.getNum());
                    hj4 += item.getNum();
                }
                if (item.getZpjg().equals("不定考核结果")) {
                    dataMap.put("nosure" + item.getRank(), item.getNum());
                    hj5 += item.getNum();
                }
                //算小记
                if (!item.getZpjg().equals("不参加") && !item.getZpjg().equals("不定考核结果")) {
                    if (xiaoji.containsKey(item.getRank())) {
                        int sum = xiaoji.get(item.getRank());
                        xiaoji.put(item.getRank(), sum + item.getNum());
                    } else {
                        xiaoji.put(item.getRank(), item.getNum());
                    }
                }
            }
            dataMap.put("good0", hj1);
            dataMap.put("pass0", hj2);
            dataMap.put("bad0", hj3);
            dataMap.put("nojoin0", hj4);
            dataMap.put("nosure0", hj5);

            int xjsum = xiaoji.get("1") + xiaoji.get("2") + xiaoji.get("3") + xiaoji.get("4");
            dataMap.put("xiaoji0", xjsum);
            dataMap.put("xiaoji1", xiaoji.get("1"));
            dataMap.put("xiaoji2", xiaoji.get("2"));
            dataMap.put("xiaoji3", xiaoji.get("3"));
            dataMap.put("xiaoji4", xiaoji.get("4"));

            dataMap.put("reson", pskhOpinion.getOpinion());
            dataMap.put("ph", pskhOpinion.getPhone());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            DocumentHandler doc = new DocumentHandler();
            String fileName = "平时考核_" + sdf.format(new Date()) + ".doc";
            String filePath = ConfigOption.getInstance().getFileurl() + "/" + fileName;
            String tempfilename = "pskhtemp.xml";//"mzpdtemp.xml";//换成导出的模板
            Boolean bolResult = doc.createObjDoc(dataMap, filePath, tempfilename);

            if (bolResult) {
                String url = ConfigOption.getInstance().getWeburl() + fileName;
                result.setCode(200);
                result.setResult(1);
                result.setMsg(url);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }

    @RequestMapping(value = "/bddc_export", method = RequestMethod.POST)
    @ResponseBody
    public ExceResult bddcExportOpinion(@RequestBody DYStatisticsList uatmzpdsummary) {
        ExceResult result = new ExceResult();
        result.setCode(400);
        result.setResult(0);

        try {
            List<DYStatistics> dyStatistics = uatmzpdsummary.getTemplatelist();
            String orgName = uatmzpdsummary.getOrgname();
            String year = uatmzpdsummary.getYearid();
            String quarter = uatmzpdsummary.getQuarter();
            String Name = orgName + "不定等次季报表(" + year + "年" + quarter + "季)";

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("orgname", orgName);
            dataMap.put("yearid", year);
            dataMap.put("quarter", quarter);

            //循环赋予值（表数据）
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            for (int i = 0; i < dyStatistics.size(); i++) {
                DYStatistics dy = dyStatistics.get(i);
                Map<String, String> item = new HashMap<>();
                item.put("num", String.valueOf(i + 1));
                item.put("orgname", dy.getOrgname());
                item.put("realname", dy.getRealname());
                item.put("age", String.valueOf(dy.getAge()));
                item.put("sexText", dy.getSexText());
                item.put("cardno", dy.getCardno());
                item.put("orgdname", dy.getOrgname());//党支部
                item.put("xrzwn", getxrzwn(dy.getXrzw()));
                if (dy.getWgwjsm() == null) dy.setWgwjsm("");
                item.put("wgwjsm", dy.getWgwjsm());
                if (dy.getRemark() == null) dy.setRemark("");
                item.put("remark", dy.getRemark());
                list.add(item);
            }
            dataMap.put("table", list);


            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

            DocumentHandler doc = new DocumentHandler();
            String fileName = Name + "_" + sdf.format(new Date()) + ".doc";
            String filePath = ConfigOption.getInstance().getFileurl() + "/" + fileName;
            String tempfilename = "bddcjbb.xml";//"mzpdtemp.xml";//换成导出的模板
            Boolean bolResult = doc.createObjDoc(dataMap, filePath, tempfilename);

            if (bolResult) {
                String url = ConfigOption.getInstance().getWeburl() + fileName;
                result.setCode(200);
                result.setResult(1);
                result.setMsg(url);
            } else {
                result.setCode(300);
                result.setResult(0);
                result.setMsg("操作失败");
            }
        } catch (Exception ex) {
            result.setCode(500);
            result.setResult(0);
            result.setMsg("操作异常");
            ex.printStackTrace();
        }
        return result;
    }


    private String getxrzwn(String wn) {
        if (wn == null) return "";
        String re = "";
        switch (wn) {
            case "1":
                re = "处级领导干部";
                break;
            case "2":
                re = "科级领导干部";
                break;
            case "3":
                re = "民警";
                break;
            case "4":
                re = "未定职务(新录用公务员)";
                break;
            case "5":
                re = "领导班子";
                break;

        }
        return re;
    }

    @ResponseBody
    @RequestMapping(value = "/saveOpinion")
    public PSKHResult saveOpinion(HttpServletRequest request) {


        List<PSKH> lst = null;
        PSKHResult result = new PSKHResult();
        try {
            int id = Integer.parseInt(request.getParameter("id"));
            String opinion = request.getParameter("opinion");
            int year = Integer.parseInt(request.getParameter("year"));
            int quarter = Integer.parseInt(request.getParameter("quarter"));
            String phone = request.getParameter("phone");
            PSKHOpinion pskhOpinion = new PSKHOpinion();
            pskhOpinion.setOpinion(opinion);
            pskhOpinion.setYear(year);
            pskhOpinion.setQuarter(quarter);
            pskhOpinion.setPhone(phone);
            pskhOpinion.setUserName(GetLoginUser().getRealname());
            if (id > 0) {
                pskhOpinion.setId(id);
                userUATZpService.updateOpinion(pskhOpinion);
            } else {
                userUATZpService.addOpinion(pskhOpinion);

            }


        } catch (Exception e) {

            String mess = e.getMessage();

        }
        // return JsonMapper.toJsonString(countlist);
        //return countlist;
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getDY")
    public LayTable<DYStatistics> getDY(HttpServletRequest request) {

        List<DYStatistics> lst = null;
        LayTable<DYStatistics> layTable = new LayTable<DYStatistics>();

        PSKHResult result = new PSKHResult();
        try {

            int year = Integer.parseInt(request.getParameter("year"));
            int quarter = Integer.parseInt(request.getParameter("quarter"));
            int dw = Integer.parseInt(request.getParameter("dw"));

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");

            List<BDDCOpinion> bddcOpinions = userUATZpService.getBDDC(year, quarter);

            //不定等次
            lst = userUATZpService.getDYList(year, quarter, dw);
            for (int i = 0; i < lst.size(); i++) {
                if (bddcOpinions.size() > 0) {
                    for (int j = 0; j < bddcOpinions.size(); j++) {
                        BDDCOpinion bddcOpinion = bddcOpinions.get(j);
                        if (bddcOpinion.getYear() == year && bddcOpinion.getQuarter() == quarter && bddcOpinion.getUserid() == lst.get(i).getUserid()) {
                            if (lst.get(i).getType() == 1) {

                                if (bddcOpinion.getRemark() == null || bddcOpinion.getRemark() == "") {

                                    lst.get(i).setRemark("预备党员");
                                } else {

                                    lst.get(i).setRemark(bddcOpinion.getRemark());
                                }
                            }
                            lst.get(i).setWgwjsm(bddcOpinion.getOpinion());
                        }

                    }

                } else {
                    if (lst.get(i).getType() == 1) {
                        lst.get(i).setRemark("预备党员");
                    }

                }
                String y = dateFormat.format(lst.get(i).getBirthday());
                DYStatistics mod = lst.get(i);

                Date date = new Date();
                mod.setAge(Integer.parseInt(dateFormat.format(date)) - Integer.parseInt(y));
                if (mod.getSex() == 0) {

                    mod.setSexText("男");
                } else {
                    mod.setSexText("女");

                }

            }
            layTable.setData(lst);

        } catch (Exception e) {


        }
        // return JsonMapper.toJsonString(countlist);
        //return countlist;
        return layTable;
    }


    @ResponseBody
    @RequestMapping(value = "/saveDBDD")
    public int addBDDC(HttpServletRequest request) {

        String json = request.getParameter("json");
        int year = Integer.parseInt(request.getParameter("year"));
        int quarter = Integer.parseInt(request.getParameter("quarter"));
        List<BDDCOpinion> list = JSON.parseArray(json, BDDCOpinion.class);

        userUATZpService.addBDDC(list, year, quarter);
        return 1;

    }


    //region 公共类

    public List<OrgEntity> GetOrgListByOrgid(Long orgid) {
        List<OrgEntity> lst = null;
        try {
            String where = " AND orgparentid=" + orgid + " OR orgid=" + orgid;
            lst = iOrgService.GetOrgListByWhere(where);
            return lst;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public List<OrgEntity> getOrgEntitiesAll() throws Exception {
        String where = "AND orgtype = 0";
        List<OrgEntity> orglst = iOrgService.GetOrgListByWhere(where);
        for (int i = 0; i < orglst.size(); i++) {
            String html = "";
            for (int j = 0; j < orglst.get(i).getLevel(); j++) {
                html += "&#12288;";
            }
            orglst.get(i).setOrgname(html + orglst.get(i).getOrgname());
        }
        return orglst;
    }

}
